# -*- coding: utf-8 -*-

from utils.operators.cluster_for_spark_sql_operator  import SparkSqlOperator
from datetime import timedelta
from jms_hi.dm.dm_shipno_weight_detail_hi import jms_dm__dm_shipno_weight_detail_hi
import pendulum
from airflow.exceptions import AirflowSkipException

cst = pendulum.timezone('Asia/Shanghai')
class ShipnoSumSparkSqlOperator(SparkSqlOperator):
    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(hours=1)

        schedule_date = ['09']

        if day.strftime('%H') not in schedule_date:
            print(f'{day.strftime("%H")} not in {schedule_date}, should skip')
            super().pre_execute(context)
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%H")} in {schedule_date}, run now')
            super().pre_execute(context)

jms_dm__dm_shipno_weight_sum_hi = ShipnoSumSparkSqlOperator(
    task_id='jms_dm__dm_shipno_weight_sum_hi',
    task_concurrency=1,
    pool_slots=2,
    master='yarn',
    name='jms_dm__dm_shipno_weight_sum_hi_{{ execution_date | date_add(1) | cst_ds }}',
    sql='jms_hi/dm/dm_shipno_weight_sum_hi/execute.hql',
    #executor_cores=2,
    executor_cores=2,
    #executor_memory='4G',
    executor_memory='2G',
    #num_executors=4,  # spark.dynamicAllocation.enabled 为 True 时，num_executors 表示最少 Executor 数
    num_executors=2,
    conf={'spark.dynamicAllocation.enabled'                  : 'true',  # 动态资源开启
          'spark.shuffle.service.enabled'                    : 'true',  # 动态资源 Shuffle 服务开启
          ##'spark.dynamicAllocation.maxExecutors'             : 16,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.maxExecutors'             : 2,
          #'spark.dynamicAllocation.maxExecutors'             : 11,  # 动态资源最大扩容 Executor 数
          'spark.dynamicAllocation.cachedExecutorIdleTimeout': 60,  # 动态资源自动释放闲置 Executor 的超时时间(s)
          'spark.sql.sources.partitionOverwriteMode'         : 'dynamic',  # 允许删改已存在的分区
          'spark.executor.memoryOverhead'                    : '1G',  # 堆外内存
          'spark.sql.shuffle.partitions'                     : 600,
          },
    hiveconf={'hive.exec.dynamic.partition'             : 'true',  # 动态分区
              'hive.exec.dynamic.partition.mode'        : 'nonstrict',
              'hive.exec.max.dynamic.partitions'        : 20,  # 每天生成 20 个分区
              'hive.exec.max.dynamic.partitions.pernode': 20,  # 每天生成 20 个分区
              },
    execution_timeout=timedelta(minutes=30),
    email=['jarl.huang@jtexpress.com','yl_bigdata@yl-scm.com'],
)

jms_dm__dm_shipno_weight_sum_hi << [
    jms_dm__dm_shipno_weight_detail_hi
]
